<template>
  <div>
    <div style="padding:30px;">
      <el-alert :closable="false" title="表单设计">
        <router-view />
      </el-alert>
    </div>
    <div>
      <el-form ref="form" :model="form" label-width="120px" size="small" :key="timestamp">
        <el-input v-model="form.id" type="hidden"></el-input>
        <el-form-item label="表单名称">
          <el-input v-model="form.name" style="width:80%"></el-input>
        </el-form-item>
        <h5 style="margin-left:53px;">表单字段：</h5>
        <div :style="'position: relative; height: '+(form.fields.length+1)*itemHeight+'px;'">
          <template v-for="(domain, index) in form.fields">
            <div>
              <vue-draggable-resizable :ref="'fd_'+index" :w="800" :h="itemHeight" :y="domain.y" :resizable="false" 
                :axis="'y'" :grid=[50,50] v-on:dragstop="onDragStop(index)" v-on:clicked="onClicked(index)"  :key="index">
                <el-form-item :label="domain.name" :key="domain.id" :prop="form[domain.id]"
                  :rules="{
                    required: domain.required, message: '不能为空', trigger: 'blur'
                  }"
                >
                  <el-input v-if="domain.type === 'TEXT'" style="width:80%"></el-input>
                  <el-input-number v-if="domain.type === 'NUMBER'" style="width:80%"></el-input-number>
                  <el-switch v-if="domain.type === 'SWITCH'" active-color="#13ce66" inactive-color="#aaaaaa"></el-switch>
                  <el-input v-if="domain.type === 'TEXTAREA'" type="textarea" style="width:80%" :rows="1"></el-input>
                  <el-select v-if="domain.type === 'SELECT'" value="" placeholder="请选择">
                    <el-option v-for="item in domain.options" :key="item.value" :label="item.name" :value="item.value"></el-option>
                  </el-select>
                  <el-checkbox-group v-if="domain.type === 'CHECKBOX'" v-model="domain.value">
                    <el-checkbox v-for="item in domain.options" :label="item.name" :key="item.name">{{ item.name }}</el-checkbox>
                  </el-checkbox-group>
                  <el-date-picker v-if="domain.type === 'DATE'" type="date" placeholder="选择日期"></el-date-picker>
                  <el-date-picker v-if="domain.type === 'DATETIME'" type="datetime" placeholder="选择日期"></el-date-picker>
                  <el-upload v-if="domain.type === 'FILE'" action="">
                    <el-button size="small" type="primary">点击上传</el-button>
                  </el-upload>
                </el-form-item>
              </vue-draggable-resizable>
              <div :style="'position:absolute; left:700px; top:'+(domain.y)+'px;'">
                <el-button @click.prevent="addDomain(index)" size="small"><i class="el-icon-plus"></i></el-button>
                <el-button @click.prevent="editDomain(index)" size="small"><i class="el-icon-edit"></i></el-button>
                <el-button @click.prevent="removeDomain(index)" size="small"><i class="el-icon-delete"></i></el-button>
              </div>
            </div>
          </template>
          <el-form-item :style="'position:absolute; top:'+(form.fields.length*itemHeight)+'px;'">
            <el-button type="primary" @click="onSubmit">保存</el-button>
            <el-button @click="onCancel">返回</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%">
      <div>
        <el-form ref="frmField" :model="frmField" size="mini">
          <el-input v-model="frmField.id" type="hidden"></el-input>
          <el-form-item :label="'标签'" :rules="{ required: true, message: '不能为空', trigger: 'blur' }" >
            <el-input v-model="frmField.name" style="width:80%"></el-input>
          </el-form-item>
          <el-form-item :label="'类型'" :rules="{ required: true, message: '不能为空', trigger: 'blur' }" >
            <el-select v-model="frmField.type" placeholder="请选择">
              <el-option
                v-for="item in field_types"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="'必填'" :rules="{ required: true, message: '不能为空', trigger: 'blur' }" >
            <el-switch v-model="frmField.required" active-color="#13ce66" inactive-color="#aaaaaa"></el-switch>
          </el-form-item>
          <div v-if="frmField.type === 'SELECT' || frmField.type === 'CHECKBOX'">
            <div>
              <h5 style="display: inline-block">字段选项：</h5>
              <el-button @click.prevent="addOptionItem" size="mini"><i class="el-icon-plus"></i></el-button>
            </div>
            <div>
              <template v-for="(option, index) in frmField.options">
                <el-row :gutter="24">
                  <el-col :span="10">
                    <el-form-item :label="'选项名'" :key="option.name"  :prop="option.name">
                      <el-input v-model="option.name" style="width:60%"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-form-item :label="'选项值'" :key="option.value"  :prop="option.value">
                      <el-input v-model="option.value" style="width:60%"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-button @click.prevent="removeOptionItem(index)" size="small"><i class="el-icon-delete"></i></el-button>
                  </el-col>
                </el-row>
              </template>
            </div>
          </div>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="saveDomain" size="small">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

import { saveForm, getForm } from '@/api/form'

export default {
  data() {
    return {
      timestamp: new Date().getTime(),
      itemHeight: 50,
      dialogVisible: false,
      newField: false,
      currentIndex: 0,
      form: {
        id: null,
        name: '新的表单',
        fields: []
      },
      frmField: {
        id: null,
        name: '字段',
        type: 'TEXT',
        required: false,
        validator: null,
        options: [],
        value: ''
      },
      field_types: [{
        value: 'TEXT',
        label: '文本'
      },{
        value: 'NUMBER',
        label: '数字'
      },{
        value: 'SELECT',
        label: '选项'
      },{
        value: 'SWITCH',
        label: '开关'
      },{
        value: 'CHECKBOX',
        label: '多选'
      },{
        value: 'TEXTAREA',
        label: '文本域'
      },{
        value: 'FILE',
        label: '附件'
      },{
        value: 'DATE',
        label: '日期'
      },{
        value: 'DATETIME',
        label: '日期时间'
      }]
    }
  },
  created() {
    const formId = this.$route.query.formId
    if (formId) {
      getForm(formId).then( data => {
        this.form = data.data
        this.loadForm(this.form.fields)
      })
    } else {
      const fields = [{
        name: '新的字段',
        type: 'TEXT'
      }]
      this.loadForm(fields)
    }
  },
  methods: {
    loadForm(fields) {
      for (var i = 0; i < fields.length; i++) {
        const field = fields[i]
        field.value = ''
        field.y = this.itemHeight * i
      }
      this.form.fields = fields
      this.timestamp = new Date().getTime()
    },
    onSubmit() {
      console.log(this.form)
      saveForm(this.form).then( data => {
        if(data.res) {
          this.$message.success('保存成功!')
          this.$router.back()
        }
      })
    },
    onCancel() {
      this.$router.back()
    },
    onDragStop(index) {
      const top = this.$refs['fd_' + index][0].$el.offsetTop
      let tmp_i = 0
      if (top % this.itemHeight === 0) {
        const fields = this.form.fields
        for (var i in fields) {
          const field = fields[i]
          if (field.y === top) {
            tmp_i = i
            break
          }
        }
        const tmp_del = fields.splice(index, 1)
        fields.splice(tmp_i, 0, tmp_del[0])
        this.loadForm(fields)
      }
    },
    addDomain(index) {
      this.currentIndex = index
      this.dialogVisible = true
      this.newField = true
    },
    saveDomain() {
      this.dialogVisible = false
      const field = Object.assign({}, this.frmField)
      if (this.newField) {
        this.form.fields.splice(this.currentIndex, 0, field)
      } else {
        this.form.fields[this.currentIndex] = field
      }
      this.loadForm(this.form.fields)
    },
    editDomain(index) {
      this.currentIndex = index
      this.dialogVisible = true
      this.newField = false
      this.frmField = this.form.fields[index]
    },
    removeDomain(index) {
      this.form.fields.splice(index, 1)
      this.loadForm(this.form.fields)
    },
    addOptionItem() {
      const len = this.frmField.options.length + 1
      this.frmField.options.push({name: '新选项' + len, value: 'new-option' + len})
    },
    removeOptionItem(index) {
      this.frmField.options.splice(index, 1)
    }
  }
}
</script>

<style scoped>
.line{
  text-align: center;
}
</style>
